package com.shuyixiao.javan8nv1.registry;

import com.shuyixiao.javan8nv1.core.NodeExecutionResult;
import com.shuyixiao.javan8nv1.model.Node;
import org.springframework.stereotype.Service;

import jakarta.annotation.PostConstruct;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class NodeRegistry {
    private final Map<String, NodeType> nodeTypes = new HashMap<>();

    @PostConstruct
    public void registerDefaultNodes() {
        // 模拟 n8n 的触发器节点
        registerNodeType(new NodeType() {
            @Override
            public String getType() {
                return "n8n-nodes-base.scheduleTrigger";
            }

            @Override
            public NodeExecutionResult execute(Node node, Map<String, List<Object>> inputs) {
                // 触发器产生初始数据
                Map<String, List<Object>> output = new HashMap<>();
                output.put("main", List.of((Object) Map.of("status", "triggered by schedule")));
                return new NodeExecutionResult("success", null, output);
            }
        });

        // 模拟 n8n 的普通动作节点
        registerNodeType(new NodeType() {
            @Override
            public String getType() {
                return "n8n-nodes-base.nasa";
            }

            @Override
            public NodeExecutionResult execute(Node node, Map<String, List<Object>> inputs) {
                System.out.println("Executing NASA node with input: " + inputs);
                // 简单地将输入数据传递到输出
                Map<String, List<Object>> output = new HashMap<>();
                List<Object> inputItems = inputs.getOrDefault("main", Collections.emptyList());
                // 假设此节点为每个输入项添加一个字段
                List<Object> outputItems = inputItems.stream()
                        .map(item -> {
                            Map<String, Object> newItem = new HashMap<>((Map<String, Object>) item);
                            newItem.put("classType", "C2.5"); // 模拟从NASA获取的数据
                            return (Object) newItem;
                        })
                        .collect(Collectors.toList());
                output.put("main", outputItems);
                return new NodeExecutionResult("success", "Fetched NASA data", output);
            }
        });

        // 模拟 n8n 的IF节点
        registerNodeType(new NodeType() {
            @Override
            public String getType() {
                return "n8n-nodes-base.if";
            }

            @Override
            public NodeExecutionResult execute(Node node, Map<String, List<Object>> inputs) {
                // IF节点根据条件将数据路由到true或false输出
                System.out.println("Executing IF node with input: " + inputs);
                Map<String, List<Object>> output = new HashMap<>();
                List<Object> inputItems = inputs.getOrDefault("main", Collections.emptyList());

                // 简化条件：检查输入数据中是否包含 classType 字段且包含 "C"
                boolean condition = inputItems.stream().anyMatch(item -> {
                    if (item instanceof Map) {
                        Object classType = ((Map<?, ?>) item).get("classType");
                        return classType instanceof String && ((String) classType).contains("C");
                    }
                    return false;
                });

                if (condition) {
                    output.put("true", inputItems); // n8n 中 IF 节点的 true/false 输出名为 0/1 或可自定义
                } else {
                    output.put("false", inputItems);
                }
                return new NodeExecutionResult("success", null, output);
            }
        });
        
        // 模拟 n8n 的 PostBin 节点
        registerNodeType(new NodeType() {
            @Override
            public String getType() { return "n8n-nodes-base.postBin"; }

            @Override
            public NodeExecutionResult execute(Node node, Map<String, List<Object>> inputs) {
                 System.out.println("Executing PostBin for node " + node.getName() + " with input: " + inputs);
                 // 最终节点，数据到此为止
                 return new NodeExecutionResult("success", "Data sent to PostBin", Collections.emptyMap());
            }
        });
    }

    public void registerNodeType(NodeType nodeType) {
        nodeTypes.put(nodeType.getType(), nodeType);
    }
    
    public NodeType getNodeType(String type) {
        NodeType nodeType = nodeTypes.get(type);
        if (nodeType == null) {
            // 提供一个默认实现来避免空指针
            return new NodeType() {
                @Override
                public String getType() {
                    return "unknown";
                }

                @Override
                public NodeExecutionResult execute(Node node, Map<String, List<Object>> inputs) {
                    System.err.println("Executing unknown node type: " + node.getType());
                    return new NodeExecutionResult("error", "Unknown node type", Collections.emptyMap());
                }
            };
        }
        return nodeType;
    }
}
